<?php
// Get the Global Vars -  now being imported in CakePHP's bootstrap.php, so no need to do it here

// legacy verison:
//require_once(dirname(__FILE__) . "/../GlobalsClass.php"); // Needed for UTK server (works w/Win too)

// Latest version:
//require_once(dirname(__FILE__) . "/../../GlobalsClass.php"); // Needed for UTK server (works w/Win too)



class HeadlessFijiMacroExecuter {
	
	
	public $debug = FALSE;
	private $macro_arg_str; // the arg to the macro - a single str with mult arg delimeted by a special char
	private $macro_name;  


	////////////////////////////////////////
	//// GETTERS & SETTERS /////////////////	    
	public function get_macro_arg_str() {  return $this->macro_arg_str;	}
	public function set_macro_arg_str($macro_str) { $this->macro_arg_str = $macro_str; }

	public function get_macro_name() {  return $this->macro_name;	}
	public function set_macro_name($macro_name)	{ $this->macro_name = $macro_name; }
	
	/////// end Getters & Setters ////////////
	//////////////////////////////////////////
	
	/////// Constructor //////////
	public function __construct($debug = FALSE){
		
		$this->debug = $debug;
    		       
	} /////// end constructor /////////////////
	
	
	function printD($str) {
		//global $debug;
		if($this->debug) print($str);
	} /////// end function printD() /////
	
	
	public function execute_macro() {
		
		$macro_name = $this->macro_name;
		$macro_arg  = $this->macro_arg_str;
		
		$macro_path       = GlobalsClass::getFijiMacroPath();
		$progNameWithPath = GlobalsClass::getFijiNameWithPath(); 
		 
		$command_str = "$progNameWithPath --headless -macro  \"$macro_path$macro_name\"  $macro_arg -batch";
		$this->printD("\n<pre>\n");
		$this->printD("\nAbout to execute system() command with arg:\n$command_str\n\n");
		flush();
		// Run the ImageJ/Fiji headless
		$last_line = system($command_str, $retval);  
		
		$this->printD("\nSystem call last line of output: \"" . $last_line . "\"");
		$this->printD("\nSystem call retval:" . $retval);
		$this->printD("\n</pre>\n");
		flush();
	} /////////// end function execute_macro()  ////////////////
	
	/*
	 * Creates and returns a single str out of mult args separated by the passed-in delimeter char
	 */
	function construct_macro_str($args_array, $args_delimeter) {
	
		$args_str = "";
		for($i = 0; $i < count($args_array); $i++) {
			// Only add the delimeter after non-last args
			if($i < (count($args_array)-1)) {
				$args_str .= "$args_array[$i]$args_delimeter";
			}
			else { // for last arg, don't append delimeter
				$args_str .= $args_array[$i];
			}
		}
		// wrapping whole str in quotes so macro receives it as one arg (macro can only get one arg)
		$args_str = "\"" . $args_str . "\"";
		
		return $args_str;
	} ////////// end function construct_macro_str() ////////
	
	
	
	
} ////////////// end class ////////////////////////////////////////////

?>